package com.soundShape.mediators.newEmployee
{
	
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.mediators.AbstractViewMediator;
	import com.soundShape.views.newEmployee.NewEmployee;
	import com.soundShape.vo.EmployeeVO;
	
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.events.ValidationResultEvent;
	
	import nz.co.codec.flexorm.criteria.Criteria;
	
	import spark.components.TextInput;
	
	
	public class NewEmployeeMediator extends AbstractViewMediator
	{
		
				
				
				private var ndxPassword:int;
				
				public function NewEmployeeMediator()
				{
					super(NewEmployee);
				}
				
				/**
				 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
				 * we need to create a local getter to access the underlying, expected view
				 * class type.
				 */
				public function get view():NewEmployee
				{
					return this._view as NewEmployee;
				}
				
				/**
				 * The <code>init()</code> method is fired off automatically by the 
				 * AbstractViewMediator when the creation complete event fires for the
				 * corresponding ViewMediator's view. This allows us to listen for events
				 * and set data bindings on the view with the confidence that our view
				 * and all of it's child views have been created and live on the stage.
				 */
				override protected function init():void
				{
					super.init();
					
					this.setViews();
					
				}
				
				override protected function setViewDataBindings():void
				{
					super.setViewDataBindings();
					
				}	
				
				override protected function setViewListeners():void
				{
					super.setViewListeners();
					
					this.view.txtInAlias.addEventListener(KeyboardEvent.KEY_UP, doKeyUpHandler);
					this.view.txtInFirstName.addEventListener(KeyboardEvent.KEY_UP, doKeyUpHandler);
					this.view.txtInLastName.addEventListener(KeyboardEvent.KEY_UP, doKeyUpHandler);
					this.view.txtInMiddleInitial.addEventListener(KeyboardEvent.KEY_UP, doKeyUpHandler);
					this.view.txtInPassword.addEventListener(KeyboardEvent.KEY_UP, doKeyUpHandler);
					
					this.view.btnSubmit.addEventListener(MouseEvent.MOUSE_OVER, doMouseOverValidation);
					
					this.view.btnSubmit.addEventListener(MouseEvent.CLICK, doSubmit);
					
					this.view.btnAdminMain.addEventListener(MouseEvent.CLICK, handleBtnLogin);
					
					this.view.txtInReEnterPassword.addEventListener(FocusEvent.FOCUS_OUT, handleReEnterPasswordFocusOut)
				
				}
				
				private function setViews():void
				{
					
				}
				
				private var arrFocus:Array = [
						{valid:false},
						{valid:false},
						{valid:false},
						{valid:false},
						{valid:false}];
				
				
				
				/**
				 * *******************************************************************************
				 * Handlers
				 * *******************************************************************************
				 */
				protected function doKeyUpHandler(keyboardEvent:KeyboardEvent):void
				{
					var nValid:int = 0;
					
					switch(TextInput(keyboardEvent.currentTarget).id)
					{
						case "txtInFirstName":
							if(ValidationResultEvent(this.view.req0.validate()).type == ValidationResultEvent.INVALID)
								this.arrFocus[0].valid = false;
							else
								this.arrFocus[0].valid = true;
							break;
						
						case "txtInMiddleInitial":
							if(ValidationResultEvent(this.view.req1.validate()).type == ValidationResultEvent.INVALID)
								this.arrFocus[1].valid = false;
							else
								this.arrFocus[1].valid = true;
							break;
						
						case "txtInLastName":
							if(ValidationResultEvent(this.view.req2.validate()).type == ValidationResultEvent.INVALID)
								this.arrFocus[2].valid = false;
							else
								this.arrFocus[2].valid = true;
							break;
						
						case "txtInAlias":
							if(ValidationResultEvent(this.view.req3.validate()).type == ValidationResultEvent.INVALID)
								this.arrFocus[3].valid = false;
							else
								this.arrFocus[3].valid = true;
							break;
						
						case "txtInPassword":
							if(ValidationResultEvent(this.view.req4.validate()).type == ValidationResultEvent.INVALID)
								this.arrFocus[4].valid = false;
							else
								this.arrFocus[4].valid = true;
								this.view.txtInReEnterPassword.enabled = true;
							break;
					}
					
					for(var i:int=0; i<this.arrFocus.length; i++)
					{
						this.view.btnSubmit.enabled = true;
						
						if(!this.arrFocus[i].valid)
						{
							this.view.btnSubmit.enabled = false;
							break;
						}
					}
				}
				
				protected function doMouseOverValidation(mouseEvent:MouseEvent):void
				{
					var nValid:int = 0;
					
					if(ValidationResultEvent(this.view.req0.validate()).type == ValidationResultEvent.INVALID)
						nValid++;
					
					if(ValidationResultEvent(this.view.req1.validate()).type == ValidationResultEvent.INVALID)
						nValid++;
					
					if(ValidationResultEvent(this.view.req2.validate()).type == ValidationResultEvent.INVALID)
						nValid++;
					
					if(ValidationResultEvent(this.view.req3.validate()).type == ValidationResultEvent.INVALID)
						nValid++;
					
					if(ValidationResultEvent(this.view.req4.validate()).type == ValidationResultEvent.INVALID)
						nValid++;
					
					(nValid>0)?this.view.btnSubmit.enabled = false:this.view.btnSubmit.enabled = true;
				}
				
				private function doSubmit(mouseEvent:MouseEvent):void
				{
					
					var soundShapeEvent:SoundShapeEvent = new SoundShapeEvent(SoundShapeEvent.SWITCH_TO_LOGIN_VIEW)
					
					var employeeVO:EmployeeVO = new EmployeeVO();
						employeeVO.firstName = this.view.txtInFirstName.text;
						employeeVO.middleName = this.view.txtInMiddleInitial.text;
						employeeVO.lastName = this.view.txtInLastName.text;
						employeeVO.alias = this.view.txtInAlias.text;
						employeeVO.password = this.view.txtInPassword.text;
						employeeVO.creatorID = this.applicationModel.employeeVO.id;
						employeeVO.role = this.view.txtInRole.text;
						
					if(isDuplicate(employeeVO))
					{
						soundShapeEvent.data = {duplicateData:true};
						this.dispatcher.dispatchEvent(soundShapeEvent);
					}
					else
					{
						soundShapeEvent.data = {duplicateData:false};
						this.dispatcher.dispatchEvent(soundShapeEvent);
						this.applicationModel.entityManager.save(employeeVO);
					}
					
					resetNewEmployeeForm();
				}
				
				private function resetNewEmployeeForm():void
				{
					this.view.txtInFirstName.text = "";
					this.view.txtInMiddleInitial.text = "";
					this.view.txtInLastName.text = "";
					this.view.txtInAlias.text = "";
					this.view.txtInPassword.text = ""; 
					this.view.txtInReEnterPassword.text = "";
					
					this.view.txtInFirstName.errorString = "";
					this.view.txtInMiddleInitial.errorString = "";
					this.view.txtInLastName.errorString = "";
					this.view.txtInAlias.errorString = "";
					this.view.txtInPassword.errorString = "";
					
					this.view.btnSubmit.enabled = false;
				}
				
				private function handleBtnLogin(mouseEvent:MouseEvent):void
				{
					this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.SWITCH_TO_ADMIN_VIEW));
					resetNewEmployeeForm();
				}
				
				private function handleReEnterPasswordFocusOut(focusEvent:FocusEvent):void
				{
					if(this.view.txtInPassword.text != this.view.txtInReEnterPassword.text)
					{
						this.view.txtInPassword.text = "";
						this.view.txtInReEnterPassword.text = "";
						this.view.txtInReEnterPassword.enabled = false;
						this.arrFocus[4].valid = false;
					}
				}
				
				private function isDuplicate(employeeVO:EmployeeVO):Boolean
				{
					var isDupe:Boolean = false;
					
					var criteria:Criteria = applicationModel.entityManager.createCriteria(EmployeeVO);
					
					var employees:ArrayCollection = applicationModel.entityManager.fetchCriteria(criteria);
					
					for each (var employee:EmployeeVO in employees)
					{
						if((employee.firstName == employeeVO.firstName) && (employee.lastName == employeeVO.lastName))
						{
							isDupe = true;
							break;
						}
							
						if((employee.alias == employeeVO.alias) && (employee.password == employeeVO.password))
						{
							isDupe = true;
							break;
						}
					}
				return isDupe;
				}
				
				/**
				 * *******************************************************************************
				 * Swiz EventHandlers
				 * *******************************************************************************
				 */
				
		}
		
	}
